package com.huifaapp.mall.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.ShareExplosionItemActivity;
import com.huifaapp.mall.afinal.Constants;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.bean.ShopList;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.ShareUtils;
import com.huifaapp.mall.uitils.UtilsImage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;


/**
 * 
* @ClassName: IntroductionPageAdapter 
* @Description: TODO(引导页) 
* @author lijs
* @date 2016年5月11日 下午1:34:37 
*
 */
public class SharewxExplosionItemListviewAdapter extends BaseAdapter {
	private Context context;
	private LayoutInflater inflater;
	private List<ShopList.DataBean.ListBean>  list;
	private IWXAPI api;
	private static final int SHARET_WXHY = 519;
	public SharewxExplosionItemListviewAdapter(Context context, List<ShopList.DataBean.ListBean> list) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.list=list;
		// 通过WXAPIFactory工厂，获取IWXAPI的实例
		api = WXAPIFactory.createWXAPI(context, Constants.WX_APPID);
		api.registerApp(Constants.WX_APPID);
	}

	@Override
	public int getCount() {
		return list == null ? 0 : list.size();
	//Integer.MAX_VALUE;
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}


	public List<ShopList.DataBean.ListBean> getList() {
		return list;
	}

	public SharewxExplosionItemListviewAdapter setList(List<ShopList.DataBean.ListBean> list) {
		this.list = list;
		return this;
	}

	int ds=0;
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (null == convertView) {
			convertView = inflater.inflate(R.layout.sharewx_explosion_item_listview, null);
			holder = new ViewHolder();
			holder.tv_Sharewx_Explosion_TimeBaopin= (TextView) convertView.findViewById(R.id.tv_Sharewx_Explosion_TimeBaopin);
			holder.tv_Sharewx_explosion_numberImage= (TextView) convertView.findViewById(R.id.tv_Sharewx_explosion_numberImage);
			holder.tv_Sharewx_Explosion_moreSend= (TextView) convertView.findViewById(R.id.tv_Sharewx_Explosion_moreSend);
			holder.tv_sharewx_look_details= (TextView) convertView.findViewById(R.id.tv_sharewx_look_details);
			holder.iv_share_item_jingping= (ImageView) convertView.findViewById(R.id.iv_share_item_jingping);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final ShopList.DataBean.ListBean bean=list.get(position);
		UtilsImage.uploadimageview(holder.iv_share_item_jingping,bean.getImg(),"",context);
		holder.tv_Sharewx_Explosion_TimeBaopin.setText(bean.getTitle());
		holder.tv_Sharewx_explosion_numberImage.setText(bean.getWord());
		holder.tv_sharewx_look_details.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent=new Intent(context,ShareExplosionItemActivity.class);
				intent.putExtra("id",bean.getId());
				intent.putExtra("skuid",bean.getSpuIds());
				context.startActivity(intent);
			}
		});
		holder.tv_Sharewx_Explosion_moreSend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ApiManager
						.getInstance()
						.getApiServer()
						.getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(context), bean.getSpuIds())
						.compose(ApiManager.<ShareImageBean>handlResult())
						.subscribe(new ObserverCallback<ShareImageBean>(context) {
							@Override
							protected void onSuccessful(ShareImageBean resp) {
								Log.e("sh","aaaaaaaaaaaaaaaa"+resp.getPoster()+ resp.getFailure()+ SHARET_WXHY+"     "+resp+"          "+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"    "+ AUniqueIdentifier.getDeviceId(context)+"        "+bean.getSpuIds());
								saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
							}

							@Override
							protected void onError(String code, String errMsg) {
								ToastUtils.showShortSafe(errMsg);
							}
						});
			}
		});
		return convertView;
	}


	class ViewHolder {
		private TextView tv_Sharewx_Explosion_TimeBaopin;
		private TextView tv_Sharewx_explosion_numberImage;
		private TextView tv_Sharewx_Explosion_moreSend;
		private TextView tv_sharewx_look_details;
		private ImageView iv_share_item_jingping;

	}
	private void saveImage(List<String> imageUrls, final String cconten, final int type) {

		Log.v("shiran","------------saveImage------------");

		final LoadingDialog dialog = new LoadingDialog(context);
		dialog.setContent("正在生成图片请稍后");

		Observable.just(imageUrls)
				.map(new Function<List<String>, List<String>>() {

					@Override
					public List<String> apply(List<String> list) throws Exception {

						List<String> paths = new ArrayList<String>();
						for (String s : list) {
							FutureTarget<File> future = Glide.with(APP.getInstance())
									.load(s)
									.downloadOnly(500, 500);
							File cacheFile = future.get();
							String uuid = UUID.randomUUID().toString();


							FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
							String pat = savePath + uuid + ".jpg";
							paths.add(pat);

						}


						return paths;
					}
				}).subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<List<String>>() {
					@Override
					public void onSubscribe(Disposable d) {
						if (dialog != null && !dialog.isShowing()) {
							dialog.show();
						}
					}

					@Override
					public void onNext(List<String> value) {
						LogUtils.e(value);
						if (dialog != null && dialog.isShowing()) {
							dialog.dismiss();
							dialog.cancel();
						}

						switch (type) {

							case SHARET_WXHY:



								ShareUtils.sharePicToFriendNoSDK(context, value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
								break;
//							case SHARET_WXPYQ:
//								ShareUtils.share9PicsToWXCircle(context, "", value);
//								break;
							default:

								break;
						}

					}

					@Override
					public void onError(Throwable e) {
						if (dialog != null && dialog.isShowing()) {
							dialog.dismiss();
							dialog.cancel();
						}
					}

					@Override
					public void onComplete() {
						if (dialog != null && dialog.isShowing()) {
							dialog.dismiss();
							dialog.cancel();
						}
					}
				});

	}


}